<template>
	<view>
		<view class="top">
			<button type="default" size="mini" @click="onChangeCity">更换城市</button>
		</view>
		
		<view class="city">{{ city }}</view>
		
		<view>
			<view v-for="item in weatherForecastList" :key="item.date" class="every-day">
				<view>{{ item.date }}</view>
				<view>{{ item.text_day }}</view>
				<view>{{ item.low }}°C - {{ item.high }}°C</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { request } from '../../request.js'
	
	export default {
		data () {
			return {
				city: '珠海',
				weatherForecastList: []
			}
		},
		
		onLoad () {
			this.getWeatherForecast(this.city)
			
			this.$EventBus.$on('chooseCity', city => {
				this.getWeatherForecast(city)
			})
		},
		
		onUnload () {
			this.$EventBus.$off('chooseCity')
		},
		
		methods: {
			getWeatherForecast (city) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				
				const payload = {
					address: 'weather/daily.json',
					method: 'GET',
					params: {
						location: city
					}
				}
				
				request(payload)
					.then(res => {
						this.city = res.data.results[0].location.name
						this.weatherForecastList = res.data.results[0].daily
					})
					.catch(err => {
						uni.showToast({
							title: '出错了',
							icon: 'none',
							mask: true
						})
					})
					.finally(() => {
						uni.hideLoading()
					})
			},
			
			onChangeCity () {
				uni.navigateTo({
					url: '/pages/choose-city/choose-city'
				})
			}
		}
	}
</script>

<style>
	.top {
		padding: 20rpx;
	}
	
	.city {
		padding: 20rpx;
		text-align: center;
		font-size: 40rpx;
		font-weight: bold;
		margin: 40rpx 0rpx;
	}
	
	.every-day {
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
	}
</style>
